package com.project.base.common;


import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


public class ClassLoaderCache {
    /**
     * 缓存已经载入的Class实例
     */
    private static Map<String, BaseSingle<Class<?>>> classCacheMap = Collections.synchronizedMap(new HashMap<String, BaseSingle<Class<?>>>());

    /**
     * 默认构造器
     */
    private ClassLoaderCache() {
    }

    /**
     * 根据类名获取该类的实例
     *
     * @param className String 类名
     * @return Object 返回的类实例
     */
    public static Object getObjectByName(String className) throws Exception {
        return getClassByName(className).newInstance();//如果没异常,newInstance时必然不会为null
    }

    /**
     * 根据类名获取该类
     *
     * @param className String 类名
     * @return Class 返回的类
     */
    public static Class<?> getClassByName(String className) throws Exception {
        className = className == null ? null : className.trim();
        if (!StringTools.isValid(className)) {
            throw new Exception("classname is not valid");
        }
        BaseSingle<Class<?>> bs = classCacheMap.get(className);//先尝试并行读
        if (bs == null) {
            synchronized (classCacheMap) {
                bs = classCacheMap.get(className);
                if (bs == null) {
                    bs = new BaseSingle<Class<?>>(null);
                    classCacheMap.put(className, bs);
                }
            }
        } else if (bs.getValue() != null) {
            return bs.getValue();
        }
        synchronized (bs) {
            if (bs.getValue() == null) {
                bs.setValue(Class.forName(className));//异常上抛
            }
        }
        return bs.getValue();
    }
}
